package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Permission;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.util.NeedPermission;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.StringExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermisisonServiceImpl implements IPermissionService{

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext atx;

   public void delete(Long id) {

        permissionMapper.deleteByPrimaryKey(id);
    }


    public List<Permission> selectList() {

        return permissionMapper.selectAll();
    }

    public PageResult queryResult(QueryObject qo) {
        Integer rows = permissionMapper.queryForCount(qo);
        //判断数据库中的记录数是否为null
        if (rows==0) {
            return PageResult.EMPRY_PAGE;
        }
        //===============
        //如果数据库中有数据
        List<Permission> data = permissionMapper.queryForPage(qo);

        return new PageResult(data,rows,qo.getCurrentPage(),qo.getPageSize());
    }

    //加载权限的方法
    public void loadRole() {

       //查询出数据库中所有的权限表达式
        List<String> exps = permissionMapper.selectExpression();
       //获取所有贴有controller注解的类
        Collection<Object> values = atx.getBeansWithAnnotation(Controller.class).values();
        //获取该类的字节码对象
        for (Object value : values) {
            Class<?> clz = value.getClass();
            //获取类中的所有方法
            Method[] method = clz.getDeclaredMethods();
            //循环迭代出所有的方法
            for (Method m : method) {
                NeedPermission anno = m.getAnnotation(NeedPermission.class);
                //添加权限表达式
                String exp = StringExpression.experssion(m);
                //判断哪些方法需要权限表达式
                if (anno!= null && !exps.contains(exp)) {
                    Permission p = new Permission();
                    p.setName(anno.value());
                    p.setExpression(exp);
                    //保存权限
                    permissionMapper.insert(p);
                }
            }
        }
    }
}
